package com.atwork.wuhua.mvp.presenter;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Handler;
import android.os.Message;
import android.widget.TextView;
import android.widget.Toast;

import com.atwork.wuhua.base.BasePresenter;
import com.atwork.wuhua.base.BaseReq;
import com.atwork.wuhua.base.MyApplication;
import com.atwork.wuhua.bean.EditInfoBean;
import com.atwork.wuhua.bean.FileLoadBean;
import com.atwork.wuhua.bean.UserBean;
import com.atwork.wuhua.bean.VerifyBean;
import com.atwork.wuhua.mvp.Callback;
import com.atwork.wuhua.mvp.DataModel;
import com.atwork.wuhua.mvp.Token;
import com.atwork.wuhua.mvp.view.IMyFragment;
import com.atwork.wuhua.utils.HttpUtil.HttpConfig;
import com.atwork.wuhua.utils.LogUtils;
import com.atwork.wuhua.utils.TimeUtil;
import com.atwork.wuhua.utils.UserUtil;
import com.google.gson.Gson;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class MyPresenter extends BasePresenter<IMyFragment> {
    //1为男,2为女,0为保密
    public void editInfo(String nickname, String gender, String avatar, String birth, String signature) {

        BaseReq req = new BaseReq();
        if (!"".equals(nickname)) {
            req.setKey("nickname", nickname);
        }
        if (!"".equals(gender)) {
            req.setKey("gender", gender);
        }
        if (!"".equals(avatar)) {
            req.setKey("avatar", avatar);
        }
        if (!"".equals(birth)) {
            req.setKey("birth", birth);
        }
        if (!"".equals(signature)) {
            req.setKey("signature", signature);
        }
        showLoading();
        if (isViewAttached() && req != null) {
            DataModel.request(Token.API_EDITINFO)
                    .params(req, false)
                    .execute(new Callback<EditInfoBean>() {


                        @Override
                        public void onSuccess(String msg, EditInfoBean data) {
                            showToast(msg);
                            getInfo();
                        }

                        @Override
                        public void onFailure(String msg) {
                            hideLoading();
                            showToast(msg);
                        }

                        @Override
                        public void onError() {

                        }

                        @Override
                        public void onComplete() {

                        }
                    });
        }
    }

    @SuppressLint("HandlerLeak")
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 0:
                    showToast("图片上传失败");
                    break;
                case 1:
//                    showToast("图片上传成功");
                    LogUtils.e("图片返回==》" + msg.obj);
                    Gson gson = new Gson();
                    FileLoadBean entity = gson.fromJson((String) msg.obj, FileLoadBean.class);
                    if (entity.getErrno().equals("000")) {
                        editInfo("", "", entity.getResult().getFile(), "", "");
                    } else {
                        showToast("图片上传失败");
                    }

                    break;
            }

            super.handleMessage(msg);

        }
    };

    public void uploadImg(String filePath) {
        OkHttpClient client = new OkHttpClient();
        // form 表单形式上传
        MultipartBody.Builder requestBody = new MultipartBody.Builder().setType(MultipartBody.FORM);
        File file = new File(filePath);
        // MediaType.parse() 里面是上传的文件类型。
        RequestBody body = RequestBody.create(MediaType.parse("image/*"), file);
        // 参数分别为， 请求key ，文件名称 ， RequestBody
        BaseReq req = new BaseReq();
        req.setKey("type", "avatar");
        String filename = "zl" + TimeUtil.getCurrentTimeMillis() + ".png";
        requestBody.addFormDataPart("file", filename, body).addFormDataPart("secret", req.getSecret());

        Request request = new Request.Builder().url(HttpConfig.BASE_URL + "common/upload").post(requestBody.build()).build();
// readTimeout("请求超时时间" , 时间单位);
        client.newBuilder().readTimeout(5000, TimeUnit.MILLISECONDS).build().newCall(request).enqueue(new okhttp3.Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Message message = new Message();
                message.what = 0;
                handler.sendMessage(message);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String string = response.body().string();
                Message message = new Message();
                message.what = 1;
                message.obj = string;
                handler.sendMessage(message);
            }


        });

    }


    /**
     * 获取用户信息
     */
    public void getInfo() {
        if (UserUtil.isLogin(getView().getContext())) {
            BaseReq req = new BaseReq();
            req.setKey("uuid", MyApplication.UUID);
            if (req != null) {
                DataModel.request(Token.API_MYINFO)
                        .params(req, false)
                        .execute(new Callback<UserBean>() {


                            @Override
                            public void onSuccess(String msg, UserBean data) {
                                hideLoading();
                                UserUtil.loginSuccess(getView().getContext(), data);
                                getView().editInfoResult();
                            }

                            @Override
                            public void onFailure(String msg) {

                            }

                            @Override
                            public void onError() {

                            }

                            @Override
                            public void onComplete() {

                            }
                        });
            }
        }
    }
}
